<script setup lang="ts">
import { Check, Delete, Edit, Message, Search, Star, } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { getWarehouse, postDeleteById, getType, getState, getFindById, updateById, add } from '@/api/WarehouseManagement'
import { onMounted, reactive, ref, watch } from 'vue'
import type { Ref } from 'vue'

// 声明百度地图类型
declare global {
  interface Window {
    BMapGL: any;
    initBMap: () => void;
  }
}

interface OptionType {
  value: string;
  label: string;
}

interface StateOption {
  value: string;
  label: string;
}

interface RuleForm {
  id: string
  companyId: any
  type: any
  name: string
  address: string
  area: string
  manager: string
  email: string
  phone: string
  state: any
  sn: string
  longitude: string  // 经度
  latitude: string   // 纬度
  maxHum: string
  minHum: string
  maxTem: string
  minTem: string
}


const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  id: '',
  companyId: '',
  type: '',
  name: '',
  address: '',
  area: '',
  manager: '',
  email: '',
  phone: '',
  state: '',
  sn: '',
  longitude: '',
  latitude: '',
  maxHum: '',
  minHum: '',
  maxTem: '',
  minTem: ''
})


const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  companyId: [
    { required: true, message: '请输入企业编号', trigger: 'blur' }
  ],
  type: [
    {
      required: true,
      message: '请输入库房类型',
      trigger: 'change',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入库房名称',
      trigger: 'blur',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    },
  ],
  area: [
    {
      required: true,
      message: '请输入库房面积',
      trigger: 'blur',
    },
  ],
  manager: [
    {
      required: true,
      message: '请输入库房负责人',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入负责人电话',
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入负责人邮箱',
      trigger: 'blur',
    },
  ],
  state: [
    {
      required: true,
      message: '请输入状态',
      trigger: 'change',
    },
  ],
  maxHum: [
    {
      required: true,
      message: '请输入最高湿度',
      trigger: 'blur',
    },
  ],
  minHum: [
    {
      required: true,
      message: '请输入最低湿度',
      trigger: 'blur',
    },
  ],
  maxTem: [
    {
      required: true,
      message: "请输入最高温度",
      trigger: 'blur',
    },
  ],
  minTem: [
    {
      required: true,
      message: "请输入最低温度",
      trigger: 'blur',
    },
  ],
})



const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ruleForm.email = ''
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


const background = ref(true)
const disabled = ref(false)
const currentId = ref('')
const optionTypeList = ref<OptionType[]>([])
const state = reactive({
  tableData: [],
  pageInfo: {
    pageNum: 1,
    pageSize: 10,
  },
  total: 0,
  optionStateList: [] as StateOption[]
})
// 查询方法
async function getInfo() {
  try {
    const response = await getWarehouse(state.pageInfo)
    if (!response?.data?.data?.rows) {
      ElMessage({
        type: 'error',
        message: '获取数据格式错误'
      })
      return
    }

    state.tableData = response.data.data.rows.map((item: any) => ({
      ...item,
      email: item?.email || '-',
      name: item?.name || '-',
      manager: item?.manager || '-',
      phone: item?.phone || '-',
      address: item?.address || '-',
      area: item?.area || '-',
      maxHum: item?.maxHum || '-',
      minHum: item?.minHum || '-',
      maxTem: item?.maxTem || '-',
      minTem: item?.minTem || '-',
      state: item?.state ?? 0
    }))

    state.total = response.data.data.total
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage({
      type: 'error',
      message: '获取仓库列表失败'
    })
  }
}

// 删除方法
function deleteById(id: any) {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const data = await postDeleteById(id)
      if (data.data.msg == "删除成功") {
        ElMessage({
          type: 'success',
          message: data.data.msg,
        })
      }
      getInfo()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

// 设置清仓
function upDateType(id: any) {
  ElMessageBox.confirm(
    '确定要清空该仓库吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    ruleForm.id = id
    const { data: { data } } = await getFindById(id)
    Object.assign(ruleForm, {
      companyId: data.companyId,
      type: data.type,
      name: data.name,
      address: data.address,
      area: data.area,
      manager: data.manager,
      phone: data.phone,
      email: data.email,
      state: 1
    })

    const { data: response } = await updateById(ruleForm)
    getInfo()

    if (response.msg == "更新成功") {
      ElMessage({
        type: 'success',
        message: response.msg,
      })
    } else {
      ElMessage({
        type: 'error',
        message: response.msg,
      })
    }
  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}


// 挂载函数
onMounted(() => {
  getInfo()
  getTypes()
  getStates()
  initMap()
})

const handleSizeChange = (val: number) => {
  state.pageInfo.pageSize = val
  getInfo()
}

const handleCurrentChange = (val: number) => {
  state.pageInfo.pageNum = val
  getInfo()
}


const dialogVisible = ref(false)

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

async function edit(id: any) {
  try {
    title.value = "修改"
    dialogVisible.value = true
    currentId.value = id
    ruleForm.id = id

    const response = await getFindById(id)
    const data = response.data.data
    if (!data) {
      throw new Error('获取仓库数据失败')
    }

    Object.assign(ruleForm, {
      companyId: data.companyId || '',
      type: data.type || '',
      name: data.name || '',
      address: data.address || '',
      area: data.area || '',
      manager: data.manager || '',
      phone: data.phone || '',
      email: data.email || '',
      state: data.state || '',
      longitude: data.longitude || '',
      latitude: data.latitude || '',
      maxHum: data.maxHum || '',
      minHum: data.minHum || '',
      maxTem: data.maxTem || '',
      minTem: data.minTem || ''

    })
  } catch (error) {
    console.error('获取仓库数据失败:', error)
    ElMessage({
      type: 'error',
      message: '获取仓库数据失败'
    })
  }
}

async function editById(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      submit()
      dialogVisible.value = false
    }
  })
  getInfo()
}

async function submit() {
  try {
    if (!ruleForm.email) {
      ElMessage({
        type: 'warning',
        message: '请输入负责人邮箱'
      })
      return
    }

    const response = title.value == "新增"
      ? await add(ruleForm)
      : await updateById(ruleForm)

    if (response.data.msg == (title.value == "新增" ? "新增成功" : "更新成功")) {
      ElMessage({
        type: 'success',
        message: response.data.msg,
      })
    } else {
      ElMessage({
        type: 'error',
        message: response.data.msg || '操作失败',
      })
    }

    await getInfo()
    dialogVisible.value = false
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage({
      type: 'error',
      message: '操作失败，请稍后重试'
    })
  }
}

const value = ref('')
const title = ref('')
/* 
const optionTypeList =  ref([]) */

//查询库存类型
async function getTypes() {
  const { data: { data } } = await getType()
  optionTypeList.value = data
}

async function getStates() {
  const { data: { data } } = await getState()
  state.optionStateList = data
}


const formInline = reactive({
  user: '',
  region: '',
  date: '',
})

const onSubmit = () => {
  console.log('submit!')
}


function adds() {
  dialogVisible.value = true
  ruleFormRef.value?.resetFields()
  ruleForm.email = ''
  title.value = "新增"
}

// 生成仓库编号的函数
function generateSn() {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `WH${timestamp}${random}`
}

async function addFormVisible() {
  dialogVisible.value = true;
  // 自动生成sn
  ruleForm.sn = generateSn();
  // 初始化经纬度为空
  ruleForm.longitude = '';
  ruleForm.latitude = '';
  // 重置表单
  ruleFormRef.value?.resetFields();
  // 延迟初始化地图，确保DOM已渲染
  setTimeout(() => {
    initMap();
  }, 300);
}
// 在 script setup 部分添加
const mapContainer = ref<HTMLElement | null>(null)
const mapLoading = ref(false)
let map: any = null
let marker: any = null

// 初始化地图
function initMap() {
  if (!mapContainer.value) return

  mapLoading.value = true

  // 如果已经加载过地图API，直接创建地图
  if (window.BMapGL) {
    createMap()
    return 
  }

  // 创建script标签
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = `https://api.map.baidu.com/api?type=webgl&v=1.0&ak=Kr6fyMwMM6HnyS85wK7bct3TCd24gf2V&callback=initBMap`

  // 定义回调函数
  window.initBMap = function () {
    createMap()
  }

  // 添加script标签到head
  document.head.appendChild(script)

  // 处理加载错误
  script.onerror = () => {
    mapLoading.value = false
    ElMessage({
      type: 'error',
      message: '地图加载失败，请检查网络连接'
    })
  }
}

// 根据地址搜索位置
function searchAddress(address: string) {
  if (!map || !address) {
    ElMessage({
      type: 'warning',
      message: '请输入有效的地址'
    })
    return
  }

  console.log('开始搜索地址:', address)

  // 创建本地搜索实例
  const localSearch = new window.BMapGL.LocalSearch(map, {
    onSearchComplete: function (results: any) {
      console.log('搜索结果:', results)

      if (results && results.getCurrentNumPois() > 0) {
        // 获取第一个搜索结果
        const firstResult = results.getPoi(0)
        const point = firstResult.point

        // 清除之前的标记点
        if (marker) {
          map.removeOverlay(marker)
        }

        // 设置地图中心点
        map.centerAndZoom(point, 15)

        // 添加新的标记点
        marker = new window.BMapGL.Marker(point)
        map.addOverlay(marker)

        // 更新表单中的地址和经纬度
        ruleForm.address = firstResult.address
        ruleForm.longitude = point.lng
        ruleForm.latitude = point.lat

        ElMessage({
          type: 'success',
          message: '地址定位成功'
        })
      } else {
        console.error('未找到地址:', address)
        ElMessage({
          type: 'warning',
          message: '未找到该地址，请检查地址是否正确'
        })
      }
    }
  })

  // 执行本地搜索
  localSearch.search(address)
}

// 创建地图实例
function createMap() {
  try {
    if (!window.BMapGL) {
      throw new Error('百度地图API未加载完成')
    }

    // 如果已存在地图实例，先销毁
    if (map) {
      map = null
    }

    // 创建地图实例
    map = new window.BMapGL.Map(mapContainer.value!)

    // 设置地图中心点和缩放级别
    const point = new window.BMapGL.Point(116.404, 39.915)
    map.centerAndZoom(point, 12)

    // 添加地图控件
    map.addControl(new window.BMapGL.ScaleControl())
    map.addControl(new window.BMapGL.ZoomControl())

    // 开启鼠标滚轮缩放
    map.enableScrollWheelZoom(true)

    // 设置3D视角
    map.setHeading(64.5)
    map.setTilt(73)

    // 如果已有地址，进行搜索
    if (ruleForm.address) {
      searchAddress(ruleForm.address)
    }

    // 添加点击事件
    map.addEventListener('click', (e: any) => {
      const point = e.latlng
      // 如果已存在标记点，先移除
      if (marker) {
        map.removeOverlay(marker)
      }
      // 添加新的标记点
      marker = new window.BMapGL.Marker(point)
      map.addOverlay(marker)

      // 更新表单中的地址和经纬度
      const geocoder = new window.BMapGL.Geocoder()
      geocoder.getLocation(point, (result: any) => {
        if (result && result.address) {
          ruleForm.address = result.address
          ruleForm.longitude = point.lng
          ruleForm.latitude = point.lat
        }
      })
    })
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage({
      type: 'error',
      message: '地图加载失败，请刷新页面重试'
    })
  } finally {
    mapLoading.value = false
  }
}

// 监听对话框显示状态
watch(dialogVisible, (newVal) => {
  if (newVal) {
    // 对话框显示时，延迟初始化地图，确保DOM已渲染
    setTimeout(() => {
      initMap()
    }, 300)
  } else {
    // 对话框关闭时，销毁地图实例
    if (map) {
      map = null
    }
  }
})

const handleDialogOpened = () => {
  // 对话框打开时，初始化地图
  setTimeout(() => {
    initMap()
  }, 300)
}

</script>

<template>
  <!-- 搜索框 -->
  <!-- 新增按钮 -->
  <el-row>
    <el-col :span="16">
      <el-icon color="#409efc">
        <HomeFilled />
      </el-icon>
      库房管理
    </el-col>

    <el-col :span="8" style="margin-bottom: 15px;">
      <div class="col-right">
        <el-button plain @click="adds()">+新增</el-button>
        <el-input class="input" style="width: 240px" placeholder="请输入企业名称" />
      </div>
    </el-col>
  </el-row>

  <el-table :data="state.tableData" style="width: 100%">
    <el-table-column label="序号" type="index" width="60px" />
    <el-table-column label="库房类型" prop="type" width="100px">
      <template #default="scope">
        <span v-if="scope.row.type == 0">冷库</span>
        <span v-if="scope.row.type == 1">恒温仓</span>
      </template>
    </el-table-column>
    <el-table-column label="库房名称" prop="name" width="100px" />
    <el-table-column label="负责人" prop="manager" width="100px" />
    <el-table-column label="联系电话" prop="phone" width="120px" />
    <el-table-column label="邮箱" prop="email" width="180px">
      <template #default="scope">
        <span>{{ scope.row.email || '-' }}</span>
      </template>
    </el-table-column>
    <el-table-column label="库房地址" prop="address" width="150px" />
    <el-table-column label="面积" prop="area" width="100px" />
    <el-table-column label="最高湿度" prop="maxHum" width="80px" />
    <el-table-column label="最低湿度" prop="minHum" width="80px" />
    <el-table-column label="最高温度" prop="maxTem" width="80px" />
    <el-table-column label="最低温度" prop="maxTem" width="80px" />
    <el-table-column label="状态" prop="state" width="80px">
      <template #default="scope">
        <span v-if="scope.row.state == 0">正常</span>
        <span v-if="scope.row.state == 1">空仓</span>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="100px">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="upDateType(scope.row.id)">
          设置空仓
        </el-button>
        <el-button link size="small" type="primary" @click="edit(scope.row.id)">
          修改
        </el-button>
        <el-button link size="small" type="primary" @click="deleteById(scope.row.id)">
          删除
        </el-button>

      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="state.pageInfo.pageNum" v-model:page-size="state.pageInfo.pageSize"
    :page-sizes="[5, 10, 15, 20]" :disabled="disabled" :background="background"
    layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />


  <!--编辑功能-->
  <el-dialog v-model="dialogVisible" :title="title" width="800" :before-close="handleClose"
    @opened="handleDialogOpened">

    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-form-inline"
      :size="formSize" status-icon>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="企业编号:" prop="companyId">
            <el-input v-model="ruleForm.companyId" placeholder="请输入企业编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库房类型:" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请输入库房类型">
              <el-option v-for="item in optionTypeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细地址:" prop="address">
            <div style="display: flex; gap: 10px;">
              <el-input v-model="ruleForm.address" type="textarea" placeholder="请输入详细地址" style="flex: 1;" />
              <el-button type="primary" @click="searchAddress(ruleForm.address)" style="height: 100%;">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="地图位置:" prop="address">
            <div v-loading="mapLoading" ref="mapContainer"
              style="width: 100%; height: 400px; border: 1px solid #dcdfe6; background-color: #f5f7fa; position: relative;">
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度:" prop="longitude">
            <el-input v-model="ruleForm.longitude" placeholder="请输入经度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度:" prop="latitude">
            <el-input v-model="ruleForm.latitude" placeholder="请输入纬度" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="库房名称:" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入库房名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库房面积:" prop="area">
            <el-input v-model="ruleForm.area" placeholder="请输入库房面积" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="库房负责人:" prop="manager">
            <el-input v-model="ruleForm.manager" placeholder="请输入库房负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人邮箱:" prop="email">
            <el-input v-model="ruleForm.email" placeholder="请输入负责人邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人电话:" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入负责人电话" />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最高湿度:" prop="maxHum">
            <el-input v-model="ruleForm.maxHum" placeholder="请输入库房最高湿度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最低湿度:" prop="minHum">
            <el-input v-model="ruleForm.minHum" placeholder="请输入库房最低湿度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高温度:" prop="maxTem">
            <el-input v-model="ruleForm.maxTem" placeholder="请输入库房最高温度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最低温度:" prop="minTem">
            <el-input v-model="ruleForm.minTem" placeholder="请输入库房最低温度" />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态:" prop="state">
            <el-select v-model="ruleForm.state" placeholder="请输入状态">
              <el-option v-for="item in state.optionStateList" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="仓库编号:" prop="sn">
            <el-input v-model="ruleForm.sn" placeholder="仓库编号" readonly />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editById(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.col-right {
  float: right;
}

.demo-form-inline .el-input {
  --el-input-width: 260px;
}

.demo-form-inline .el-select {
  --el-select-width: 260px;
}

/* 添加地图容器样式 */
#mapContainer {
  width: 100%;
  height: 400px;
  position: relative;
  overflow: hidden;
}
</style>